/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb;

import entities.Category;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author ervaka
 */
@Stateless
public class CategoryBean implements CategoryBeanLocal {

    @PersistenceContext(unitName = "Tiendalia-ejbPU")
    private EntityManager em;

    @Override
    public List<Category> findAll() {
        Query q = em.createNamedQuery("Category.findAll");
        return q.getResultList();
    }

    public List<Category> findAllVisible() {
        Query q = em.createNamedQuery("Category.findAllVisible");
        return q.getResultList();
    }

    @Override
    public Category findById(Short id) {
        Query q = em.createNamedQuery("Category.findById");
        q.setParameter("id", id);
        return (Category) q.getSingleResult();
    }

    @Override
    public Category findByName(String name) {
        Category result;
        Query q = em.createNamedQuery("Category.findByName");
        q.setParameter("name", name);
        try {
            result = (Category) q.getSingleResult();
        } catch (NoResultException e) {
            result = null;
        }
        return result;
    }

    @Override
    public Category getChildren(Category c) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Category insert(Category category) {
        return update(category);
    }

    @Override
    public Category update(Category category) {
        return em.merge(category);
    }
}
